package com.spark.common.config;

import com.spark.common.config.serializer.FastJson2JsonRedisSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Rides配置类
 *
 * @author LYCHEE
 * @date 2025/2/14 15:52
 */
@Slf4j
@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        log.info("---------> Redis init...");
        //  创建一个新的RedisTemplate实例，用于操作Redis
        RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
        // 设置RedisTemplate使用的连接工厂，以便它能够连接到Redis服务器
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        // 调用RedisTemplate的afterPropertiesSet方法，该方法会执行一些初始化操作，比如检查序列化器是否设置等
        template.afterPropertiesSet();
        return template;
    }
}
